/**
 * 用户相关API接口
 */

import { request, mockSuccess, mockError } from '@/utils/request'

/**
 * 用户登录
 * @param {object} data - 登录数据
 * @param {string} data.username - 用户名
 * @param {string} data.password - 密码
 * @returns {Promise} 登录结果
 */
export const login = (data) => {
  return request.post('/user/login', data, {}, (params) => {
    // 模拟登录验证
    const { username, password } = params
    
    if (!username || !password) {
      return mockError('用户名和密码不能为空', 400)
    }
    
    if (username === 'admin' && password === '123456') {
      return mockSuccess({
        token: 'mock-token-' + Date.now(),
        userInfo: {
          id: 1,
          username: 'admin',
          nickname: '管理员',
          avatar: 'https://avatars.githubusercontent.com/u/1?v=4',
          email: 'admin@example.com',
          phone: '13800138000',
          department: '管理部',
          position: '系统管理员',
          roles: ['admin'],
          permissions: ['*'],
          lastLoginTime: new Date().toISOString(),
          createTime: '2024-01-01T00:00:00.000Z'
        }
      }, '登录成功')
    } else {
      return mockError('用户名或密码错误', 401)
    }
  })
}

/**
 * 用户注册
 * @param {object} data - 注册数据
 * @param {string} data.username - 用户名
 * @param {string} data.password - 密码
 * @param {string} data.email - 邮箱
 * @param {string} data.phone - 手机号
 * @returns {Promise} 注册结果
 */
export const register = (data) => {
  return request.post('/user/register', data, {}, (params) => {
    const { username, password, email, phone } = params
    
    if (!username || !password || !email || !phone) {
      return mockError('请填写完整的注册信息', 400)
    }
    
    return mockSuccess({
      id: Date.now(),
      username,
      email,
      phone,
      status: 1
    }, '注册成功')
  })
}

/**
 * 用户登出
 * @returns {Promise} 登出结果
 */
export const logout = () => {
  return request.post('/user/logout', {}, {}, () => {
    return mockSuccess(null, '登出成功')
  })
}

/**
 * 获取用户信息
 * @returns {Promise} 用户信息
 */
export const getUserInfo = () => {
  return request.get('/user/info', {}, {}, () => {
    return mockSuccess({
      id: 1,
      username: 'admin',
      nickname: '管理员',
      avatar: 'https://avatars.githubusercontent.com/u/1?v=4',
      email: 'admin@example.com',
      phone: '13800138000',
      department: '管理部',
      position: '系统管理员',
      roles: ['admin'],
      permissions: ['*'],
      lastLoginTime: new Date().toISOString(),
      createTime: '2024-01-01T00:00:00.000Z'
    })
  })
}

/**
 * 更新用户信息
 * @param {object} data - 用户信息
 * @returns {Promise} 更新结果
 */
export const updateUserInfo = (data) => {
  return request.put('/user/info', data, {}, (params) => {
    return mockSuccess({
      ...params,
      updateTime: new Date().toISOString()
    }, '更新成功')
  })
}

/**
 * 修改密码
 * @param {object} data - 密码数据
 * @param {string} data.oldPassword - 旧密码
 * @param {string} data.newPassword - 新密码
 * @returns {Promise} 修改结果
 */
export const changePassword = (data) => {
  return request.put('/user/password', data, {}, (params) => {
    const { oldPassword, newPassword } = params
    
    if (!oldPassword || !newPassword) {
      return mockError('旧密码和新密码不能为空', 400)
    }
    
    if (oldPassword === newPassword) {
      return mockError('新密码不能与旧密码相同', 400)
    }
    
    return mockSuccess(null, '密码修改成功')
  })
}

/**
 * 上传头像
 * @param {FormData} formData - 头像文件
 * @returns {Promise} 上传结果
 */
export const uploadAvatar = (formData) => {
  return request.upload('/user/avatar', formData, {}, () => {
    return mockSuccess({
      url: 'https://avatars.githubusercontent.com/u/' + Math.floor(Math.random() * 1000) + '?v=4',
      filename: 'avatar.jpg',
      size: 102400,
      uploadTime: new Date().toISOString()
    }, '头像上传成功')
  })
}

/**
 * 获取用户列表
 * @param {object} params - 查询参数
 * @param {number} params.page - 页码
 * @param {number} params.pageSize - 每页数量
 * @param {string} params.keyword - 搜索关键词
 * @returns {Promise} 用户列表
 */
export const getUserList = (params = {}) => {
  return request.get('/user/list', params, {}, (queryParams) => {
    const { page = 1, pageSize = 20, keyword = '' } = queryParams
    
    // 模拟用户数据
    const mockUsers = Array.from({ length: 50 }, (_, index) => ({
      id: index + 1,
      username: `user${index + 1}`,
      nickname: `用户${index + 1}`,
      avatar: `https://avatars.githubusercontent.com/u/${index + 1}?v=4`,
      email: `user${index + 1}@example.com`,
      phone: `138${String(index + 1).padStart(8, '0')}`,
      department: ['管理部', '财务部', '人事部', '技术部'][index % 4],
      position: ['经理', '主管', '专员', '助理'][index % 4],
      status: Math.random() > 0.2 ? 1 : 0,
      createTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
      lastLoginTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString()
    }))
    
    // 过滤数据
    let filteredUsers = mockUsers
    if (keyword) {
      filteredUsers = mockUsers.filter(user => 
        user.username.includes(keyword) || 
        user.nickname.includes(keyword) ||
        user.email.includes(keyword) ||
        user.phone.includes(keyword)
      )
    }
    
    // 分页
    const total = filteredUsers.length
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const list = filteredUsers.slice(start, end)
    
    return mockSuccess({
      list,
      total,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: Math.ceil(total / pageSize)
    })
  })
}

/**
 * 获取用户详情
 * @param {number} id - 用户ID
 * @returns {Promise} 用户详情
 */
export const getUserDetail = (id) => {
  return request.get(`/user/${id}`, {}, {}, () => {
    return mockSuccess({
      id: Number(id),
      username: `user${id}`,
      nickname: `用户${id}`,
      avatar: `https://avatars.githubusercontent.com/u/${id}?v=4`,
      email: `user${id}@example.com`,
      phone: `138${String(id).padStart(8, '0')}`,
      department: '技术部',
      position: '高级工程师',
      status: 1,
      roles: ['user'],
      permissions: ['read'],
      createTime: '2024-01-01T00:00:00.000Z',
      updateTime: new Date().toISOString(),
      lastLoginTime: new Date().toISOString()
    })
  })
}

/**
 * 创建用户
 * @param {object} data - 用户数据
 * @returns {Promise} 创建结果
 */
export const createUser = (data) => {
  return request.post('/user', data, {}, (params) => {
    return mockSuccess({
      id: Date.now(),
      ...params,
      createTime: new Date().toISOString()
    }, '用户创建成功')
  })
}

/**
 * 更新用户
 * @param {number} id - 用户ID
 * @param {object} data - 用户数据
 * @returns {Promise} 更新结果
 */
export const updateUser = (id, data) => {
  return request.put(`/user/${id}`, data, {}, (params) => {
    return mockSuccess({
      id: Number(id),
      ...params,
      updateTime: new Date().toISOString()
    }, '用户更新成功')
  })
}

/**
 * 删除用户
 * @param {number} id - 用户ID
 * @returns {Promise} 删除结果
 */
export const deleteUser = (id) => {
  return request.delete(`/user/${id}`, {}, () => {
    return mockSuccess(null, '用户删除成功')
  })
}

/**
 * 批量删除用户
 * @param {Array} ids - 用户ID数组
 * @returns {Promise} 删除结果
 */
export const batchDeleteUsers = (ids) => {
  return request.delete('/user/batch', { ids }, () => {
    return mockSuccess(null, `成功删除${ids.length}个用户`)
  })
}

/**
 * 重置用户密码
 * @param {number} id - 用户ID
 * @returns {Promise} 重置结果
 */
export const resetUserPassword = (id) => {
  return request.put(`/user/${id}/password/reset`, {}, {}, () => {
    return mockSuccess({
      newPassword: '123456'
    }, '密码重置成功，新密码为：123456')
  })
}

/**
 * 启用/禁用用户
 * @param {number} id - 用户ID
 * @param {number} status - 状态（1启用，0禁用）
 * @returns {Promise} 操作结果
 */
export const toggleUserStatus = (id, status) => {
  return request.put(`/user/${id}/status`, { status }, {}, () => {
    return mockSuccess(null, status === 1 ? '用户已启用' : '用户已禁用')
  })
}